from __future__ import absolute_import
import logging
from os.path import join, exists
from forest.api import Command, get_tool
logger = logging.getLogger('forest.commands.Format')
#from time import sleep
import os

class FormatCommand(Command):
    ''' Creates the filesystem resources defined.
    '''

    __register__ = 'commands.install.Format'

    requires_config = ['install_mode']

    def run(self, config):
        # TODO: always mount the root first
        installtree = config.get_install_root()

        filesystems = list(config.get_resources().iter_by_type('filesystem'))

        if not filesystems:
            return

        root_part = None

        print 'our filesystems', filesystems

        # format the partitions as per specification and find the root part
        for p in filesystems:

            if p.get_mount() == '/':
                root_part = p

            get_tool('system.format')(os.path.join('/dev', p.get_device()) , p.get_type())

        #XXX ad-hoc
        #sleep(10)

        # mount the root first
        get_tool('system.mount')(os.path.join('/dev', root_part.get_device()), installtree, root_part.get_type())

        # notify forest commands of the mounts
        config.set('_mounted', [installtree])

        # mount the other filesystems
        for p in filesystems:
            if p.get_mount() == '/' or p.get_type() == 'swap':
                continue

            dest = join(installtree, p.get_mount().lstrip('/'))

            if not exists(dest):
                get_tool('system.mkdir')(dest)

            # join needs the strip so the second it relative
            get_tool('system.mount')(os.path.join('/dev', p.get_device()), dest, p.get_type())

            config.set('_mounted', config.get('_mounted', []) + [dest])

